<script setup>
import { artEditChannelService, artAddChannelService } from '@/api/article'
import { ref, reactive, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
const dialogVisible = ref(false)
let formModel = ref({})
const formRenderer = ref()
const emit = defineEmits(['success'])
// 打开
const open = async (row) => {
  dialogVisible.value = true
  // 为了保证初始化的时候为一个空对象方便重置
  await nextTick()
  formModel.value = { ...row }

  console.log(formModel.value, '打开')
}
// 提交
const onSubmit = async () => {
  try {
    await formRenderer.value.methods.validate()
    formModel.value.id
      ? await artEditChannelService(formModel.value)
      : await artAddChannelService(formModel.value)
    ElMessage({
      type: 'success',
      message: formModel.value.id ? '编辑成功' : '添加成功'
    })
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.log(error)
  }
}
// 关闭
const handleClose = () => {
  console.log('重置=====')
  formModel.value = {}
  formRenderer.value.resetFields()
}
// 表单
const content = reactive([
  {
    type: 'input',
    id: 'cate_name',
    label: '分类名称',
    el: {
      minlength: '1',
      maxlength: '10'
    },
    rules: [
      { required: true, message: '请输入分类名称', trigger: 'blur' },
      {
        pattern: /^\S{1,10}$/,
        message: '分类名必须是1-10位的非空字符',
        trigger: 'blur'
      }
    ]
  },
  {
    type: 'input',
    id: 'cate_alias',
    label: '分类别名',
    el: {
      minlength: '1',
      maxlength: '15'
    },
    rules: [
      { required: true, message: '请输入分类别名', trigger: 'blur' },
      {
        pattern: /^[a-zA-Z0-9]{1,15}$/,
        message: '分类别名必须是1-15位的字母数字',
        trigger: 'blur'
      }
    ]
  }
])
defineExpose({
  open
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formModel.id ? '编辑分类' : '添加分类'"
    @close="handleClose"
    width="30%"
  >
    <el-form-renderer
      label-width="100px"
      :content="content"
      ref="formRenderer"
      style="padding-right: 30px"
      v-model:FormData="formModel"
    >
    </el-form-renderer>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button @click="onSubmit" type="primary"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
